﻿// WebcamCaptureOpenCv
//
// Webcam capturing wrapper for OpenCV library 
// 
// This is a legacy class an will probably be 
// replaced by WebcamCaptureAForge

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FLMScan.OpenCV;
using FLMScan.Exception;
using FLMScan.Capture;


namespace FLMScan.OpenCV
{
    class WebcamCaptureOpenCv : IDisposable
    {
        private bool isDisposed = false;
        private CvCapture capture;

        public WebcamCaptureOpenCv(int deviceIndex, int resolutionX, int resolutionY)
        {
            capture = CaptureWrapperOpenCV.CvCreateCameraCapture(deviceIndex);

            if (capture.ptr != null)
            {
                // Note: the problem with OpenCv is, that the code below is crashing 
                // if no camera is connected. 
                // This was the reason for no longer using OpenCV for webcam capturing                
                CaptureWrapperOpenCV.CvSetCaptureProperty(ref capture, OpenCVConstants.CV_CAP_PROP_FRAME_WIDTH, resolutionX);
                CaptureWrapperOpenCV.CvSetCaptureProperty(ref capture, OpenCVConstants.CV_CAP_PROP_FRAME_HEIGHT, resolutionY);
            }
            else
            {
                throw new CaptureException("Failed to initialize OpenCV capture!");
            }
        }

        public CapturedFrame GetFrame()
        {
            CapturedFrame frame = new CapturedFrame(CaptureWrapperOpenCV.CvQueryFrame(ref capture));

            if (frame.IsValidFrame())
            {
                frame.Bitmap = CaptureWrapperOpenCV.ToBitmap(frame.Frame, false);
            }

            return frame;
        }

        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    System.Diagnostics.Debug.Assert(capture.ptr != IntPtr.Zero);

                    CaptureWrapperOpenCV.CvReleaseCapture(ref capture);
                    capture.ptr = IntPtr.Zero;
                    isDisposed = true;
                }
            }
        }
    }
}
